﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
using System.Configuration;

namespace Genesi
{

    public partial class login : System.Web.UI.Page
    {

        SqlConnection cn;
        protected void Page_Load(object sender, EventArgs e)
        {
            cn = new SqlConnection(ConfigurationManager.ConnectionStrings["CnCrm"].ConnectionString);
            if (!IsPostBack)
            {
                Session["primapagina"] = true;
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            bool cpwd = false;
            bool accesso = Autentica(TextBox1.Text, TextBox2.Text, ref cpwd);
            // bool accesso = AutenticaTest(TextBox1.Text, TextBox2.Text);
            if (accesso & cpwd == false)
            {
                SqlCommand cmd = new SqlCommand("select name from account where accountnumber='" + TextBox1.Text + "'", cn);
                cn.Open();
                string userName = cmd.ExecuteScalar().ToString();
                cn.Close();
                Session["mostramenu"] = true;

                SqlCommand cmdXShop = new SqlCommand("select isnull(new_xshopaccess,0) from account where accountnumber='" + TextBox1.Text + "'", cn);
                cn.Open();
                try
                {
                    if (Convert.ToBoolean(cmdXShop.ExecuteScalar().ToString()))
                    {
                        Session["xshop"] = true;
                    }
                    else
                    {
                        Session["xshop"] = false;
                    }
                }
                catch
                {
                    Session["xshop"] = false;
                }
                cn.Close();
                // Session["xshop"] = true;
                Session["PIVA"] = TextBox1.Text;
                Session["user_Password"] = TextBox2.Text;
                Session["user_ID"] = TextBox1.Text;
                Session["Username"] = userName;
                FormsAuthentication.RedirectFromLoginPage(userName, false);

            }
            else if (accesso & cpwd)
            {
                tblLogin.Visible = false;
                tblCambia.Visible = true;
            }
            else if (accesso == false)
            {
                lbl_Err.Text = "Nome utente o password errati";
            }

        }

        bool Autentica(string userName, string password, ref bool cambiapassword)
        {
            bool Ris = false;
            SqlCommand cmd = new SqlCommand("select isnull(accountID,'') as accountID from account where lower(accountnumber)=lower('" + userName.Replace("'", "''") + "') and new_extranetaccess=1 and new_password='" + password.Replace("'", "''") + "'", cn);
            //  Response.Write(cmd.CommandText  + "<br>");
            cn.Open();
            try
            {
                string i = cmd.ExecuteScalar().ToString();
                if (i != "")
                {
                    Session["accountId"] = i;
                    SqlCommand cmdPwd = new SqlCommand("select count(*) from account where accountnumber=new_password and lower(accountnumber)=lower('" + userName + "')", cn);
                    // Response.Write(cmdPwd.CommandText  + "<br>");
                    Ris = true;
                    int x = Convert.ToInt32(cmdPwd.ExecuteScalar().ToString());
                    if (x > 0)
                    {
                        cambiapassword = true;
                        Session["user_ID"] = userName;
                    }
                    else
                    {
                        cambiapassword = false;
                    }
                    mailboxExchangeEnabled(i);
                    reevoBackupEnabled(i);
                    reevoLogEnabled(i);

                }
                else
                {
                    Session["accountId"] = null;
                    Ris = false;
                }
                SqlCommand cmdFattScad = new SqlCommand("SELECT count(*) as scadute from extranet.dbo.vw_Invoice WHERE duedate <= getdate() and statecode='Attiva' and (cast([AccountId] as varchar(100)) = '" + i.ToString() + "')", cn);

                if (Convert.ToInt32(cmdFattScad.ExecuteScalar()) > 0)
                {
                    Session["fatturescadute"] = true;
                }
                else
                {
                    Session["fatturescadute"] = false;
                }


            }
            catch (Exception ex)
            {
                //   Response.Write(ex.Message);
                Session["accountId"] = null;
                Ris = false;
            }
            cn.Close();
            return Ris;
        }

        bool AutenticaTest(string userName, string password)
        {
            SqlCommand cmd = new SqlCommand("select isnull(accountID,'') as accountID from account where lower(accountnumber)=lower('" + userName + "')", cn);

            cn.Open();
            string i = cmd.ExecuteScalar().ToString();
            cn.Close();
            if (i != "")
            {
                Session["accountId"] = i;
                return true;
            }
            else
            {
                Session["accountId"] = null;
                return false;
            }
        }

        protected void ButtonCambia_Click(object sender, EventArgs e)
        {
            SqlCommand cmdChangePwd = new SqlCommand("update account set new_password='" + txtnewPassword.Text + "' where accountnumber='" + TextBox1.Text + "'", cn);
            SqlCommand cmd = new SqlCommand("select name from account where accountnumber='" + TextBox1.Text + "'", cn);
            cn.Open();
            cmdChangePwd.ExecuteNonQuery();
            string userName = cmd.ExecuteScalar().ToString();
            cn.Close();
            Session["mostramenu"] = true;

            SqlCommand cmdXShop = new SqlCommand("select new_xshopaccess from account where accountnumber='" + TextBox1.Text + "'", cn);
            cn.Open();
            try
            {
                bool accessoxshop = Convert.ToBoolean(cmdXShop.ExecuteScalar().ToString());
                if (accessoxshop)
                {
                    Session["xshop"] = true;
                }
                else
                {
                    Session["xshop"] = false;
                }
            }
            catch
            {
                Session["xshop"] = false;
            }
            cn.Close();








            FormsAuthentication.RedirectFromLoginPage(userName, false);
        }

        void mailboxExchangeEnabled(string accountid)
        {

            if (accountadmin(accountid))
            {
                Session["mailboxExchangeEnabled"] = true;
            }
            else
            {
                SqlCommand cmd = new SqlCommand("select count(c.AccountId) from ContractDetail d inner join Product p on p.ProductId = d.ProductId inner join [Contract] c on c.ContractId  = d.ContractId  where p.Name like '%mailbox exchange%' and c.StateCode=2 and c.StatusCode =3 and c.AccountId='" + accountid + "'", cn);
                int c = Int32.Parse(cmd.ExecuteScalar().ToString());
                if (c > 0)
                {
                    Session["mailboxExchangeEnabled"] = true;
                }
                else
                {
                    Session["mailboxExchangeEnabled"] = false;
                }
            }
        }

        void reevoBackupEnabled(string accountid)
        {

            if (accountadmin(accountid))
            {
                Session["reevoBackupEnabled"] = true;
            }
            else
            {
                SqlCommand cmd = new SqlCommand("select count(c.AccountId) from ContractDetail d left join Product p on p.ProductId = d.ProductId inner join [Contract] c on c.ContractId  = d.ContractId  where (p.Name like '%ReeVO Backup Enterprise%'  or p.Name like '%ReeVO Backup Standard%' or d.Title like '%reevo backup%' )  and c.StateCode=2 and c.StatusCode =3 and c.AccountId='" + accountid + "'", cn);
                int c = Int32.Parse(cmd.ExecuteScalar().ToString());
                if (c > 0)
                {
                    Session["reevoBackupEnabled"] = true;
                }
                else
                {
                    Session["reevoBackupEnabled"] = false;
                }
            }
        }

        void reevoLogEnabled(string accountid)
        {

            if (accountadmin(accountid))
            {
                Session["reevoLogEnabled"] = true;
            }
            else
            {
                SqlCommand cmd = new SqlCommand("select count(c.AccountId) from ContractDetail d left join Product p on p.ProductId = d.ProductId inner join [Contract] c on c.ContractId  = d.ContractId  where (p.Name like '%log%' or d.Title like '%log%' )  and c.StateCode=2 and c.StatusCode =3 and c.AccountId='" + accountid + "'", cn);
                int c = Int32.Parse(cmd.ExecuteScalar().ToString());
                if (c > 0)
                {
                    Session["reevoBackupEnabled"] = true;
                }
                else
                {
                    Session["reevoBackupEnabled"] = false;
                }
            }
        }


        bool accountadmin(string accountid)
        {
            bool admin = false;
            if (accountid.ToUpper() == "1E02735C-A3FB-DA11-AB8E-0011D882F1AC" || accountid.ToUpper() == "63125E98-761A-DD11-81C9-0011D882F1AC")
            {
                admin = true;
            }
            return admin;
        }
    }
}